{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kR-4eNdK6lYS"
   },
   "source": [
    "Deep Learning\n",
    "=============\n",
    "\n",
    "Assignment 3\n",
    "------------\n",
    "\n",
    "Previously in `2_fullyconnected.ipynb`, you trained a logistic regression and a neural network model.\n",
    "\n",
    "The goal of this assignment is to explore regularization techniques."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "JLpLa8Jt7Vu4"
   },
   "outputs": [],
   "source": [
    "# These are all the modules we'll be using later. Make sure you can import them\n",
    "# before proceeding further.\n",
    "from __future__ import print_function\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from six.moves import cPickle as pickle"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "1HrCK6e17WzV"
   },
   "source": [
    "First reload the data we generated in _notmist.ipynb_."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 1
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 11777,
     "status": "ok",
     "timestamp": 1449849322348,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "y3-cj1bpmuxc",
    "outputId": "e03576f1-ebbe-4838-c388-f1777bcc9873"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set (200000, 28, 28) (200000,)\n",
      "Validation set (10000, 28, 28) (10000,)\n",
      "Test set (10000, 28, 28) (10000,)\n"
     ]
    }
   ],
   "source": [
    "pickle_file = 'notMNIST.pickle'\n",
    "\n",
    "with open(pickle_file, 'rb') as f:\n",
    "  save = pickle.load(f)\n",
    "  train_dataset = save['train_dataset']\n",
    "  train_labels = save['train_labels']\n",
    "  valid_dataset = save['valid_dataset']\n",
    "  valid_labels = save['valid_labels']\n",
    "  test_dataset = save['test_dataset']\n",
    "  test_labels = save['test_labels']\n",
    "  del save  # hint to help gc free up memory\n",
    "  print('Training set', train_dataset.shape, train_labels.shape)\n",
    "  print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
    "  print('Test set', test_dataset.shape, test_labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "L7aHrm6nGDMB"
   },
   "source": [
    "Reformat into a shape that's more adapted to the models we're going to train:\n",
    "- data as a flat matrix,\n",
    "- labels as float 1-hot encodings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 1
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 11728,
     "status": "ok",
     "timestamp": 1449849322356,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "IRSyYiIIGIzS",
    "outputId": "3f8996ee-3574-4f44-c953-5c8a04636582"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set (200000, 784) (200000, 10)\n",
      "Validation set (10000, 784) (10000, 10)\n",
      "Test set (10000, 784) (10000, 10)\n"
     ]
    }
   ],
   "source": [
    "image_size = 28\n",
    "num_labels = 10\n",
    "\n",
    "def reformat(dataset, labels):\n",
    "  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)\n",
    "  # Map 2 to [0.0, 1.0, 0.0 ...], 3 to [0.0, 0.0, 1.0 ...]\n",
    "  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n",
    "  return dataset, labels\n",
    "train_dataset, train_labels = reformat(train_dataset, train_labels)\n",
    "valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\n",
    "test_dataset, test_labels = reformat(test_dataset, test_labels)\n",
    "print('Training set', train_dataset.shape, train_labels.shape)\n",
    "print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
    "print('Test set', test_dataset.shape, test_labels.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "RajPLaL_ZW6w"
   },
   "outputs": [],
   "source": [
    "def accuracy(predictions, labels):\n",
    "  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n",
    "          / predictions.shape[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "sgLbUAQ1CW-1"
   },
   "source": [
    "---\n",
    "Problem 1\n",
    "---------\n",
    "\n",
    "Introduce and tune L2 regularization for both logistic and neural network models. Remember that L2 amounts to adding a penalty on the norm of the weights to the loss. In TensorFlow, you can compute the L2 loss for a tensor `t` using `nn.l2_loss(t)`. The right amount of regularization should improve your validation / test accuracy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's start with logistic regression first.  The only change from lab 2 is the regularizer.  Note that I didn't tune the hyperparamter (beta) so the test accuracy is actually slightly worse in this case."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "learning_rate = 0.5\n",
    "beta = 0.05\n",
    "\n",
    "graph = tf.Graph()\n",
    "with graph.as_default():\n",
    "\n",
    "  # Input data. For the training data, we use a placeholder that will be fed\n",
    "  # at run time with a training minibatch.\n",
    "  tf_train_dataset = tf.placeholder(tf.float32,\n",
    "                                    shape=(batch_size, image_size * image_size))\n",
    "  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "  tf_valid_dataset = tf.constant(valid_dataset)\n",
    "  tf_test_dataset = tf.constant(test_dataset)\n",
    "  \n",
    "  # Variables.\n",
    "  weights = tf.Variable(\n",
    "    tf.truncated_normal([image_size * image_size, num_labels]))\n",
    "  biases = tf.Variable(tf.zeros([num_labels]))\n",
    "  \n",
    "  # Training computation.\n",
    "  logits = tf.matmul(tf_train_dataset, weights) + biases\n",
    "  loss = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "\n",
    "  # Add the regularization term to the loss.\n",
    "  loss += beta * tf.nn.l2_loss(weights)\n",
    "  \n",
    "  # Optimizer.\n",
    "  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n",
    "  \n",
    "  # Predictions for the training, validation, and test data.\n",
    "  train_prediction = tf.nn.softmax(logits)\n",
    "  valid_prediction = tf.nn.softmax(\n",
    "    tf.matmul(tf_valid_dataset, weights) + biases)\n",
    "  test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This part is the exact same as lab 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 171.807022\n",
      "Minibatch accuracy: 6.2%\n",
      "Validation accuracy: 9.8%\n",
      "Minibatch loss at step 500: 0.944785\n",
      "Minibatch accuracy: 78.1%\n",
      "Validation accuracy: 78.8%\n",
      "Minibatch loss at step 1000: 0.881135\n",
      "Minibatch accuracy: 82.8%\n",
      "Validation accuracy: 79.2%\n",
      "Minibatch loss at step 1500: 0.883581\n",
      "Minibatch accuracy: 84.4%\n",
      "Validation accuracy: 79.9%\n",
      "Minibatch loss at step 2000: 0.909441\n",
      "Minibatch accuracy: 77.3%\n",
      "Validation accuracy: 79.2%\n",
      "Minibatch loss at step 2500: 0.906707\n",
      "Minibatch accuracy: 85.2%\n",
      "Validation accuracy: 79.9%\n",
      "Minibatch loss at step 3000: 1.037380\n",
      "Minibatch accuracy: 78.1%\n",
      "Validation accuracy: 79.0%\n",
      "Test accuracy: 85.4%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 3001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print(\"Initialized\")\n",
    "  for step in range(num_steps):\n",
    "    # Pick an offset within the training data, which has been randomized.\n",
    "    # Note: we could use better randomization across epochs.\n",
    "    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "    # Generate a minibatch.\n",
    "    batch_data = train_dataset[offset:(offset + batch_size), :]\n",
    "    batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "    # Prepare a dictionary telling the session where to feed the minibatch.\n",
    "    # The key of the dictionary is the placeholder node of the graph to be fed,\n",
    "    # and the value is the numpy array to feed to it.\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "    if (step % 500 == 0):\n",
    "      print(\"Minibatch loss at step %d: %f\" % (step, l))\n",
    "      print(\"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels))\n",
    "      print(\"Validation accuracy: %.1f%%\" % accuracy(\n",
    "        valid_prediction.eval(), valid_labels))\n",
    "  print(\"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's try the same thing for the neural network model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "hidden_nodes = 1024\n",
    "learning_rate = 0.5\n",
    "beta = 0.005\n",
    "\n",
    "graph = tf.Graph()\n",
    "with graph.as_default():\n",
    "\n",
    "  # Input data. For the training data, we use a placeholder that will be fed\n",
    "  # at run time with a training minibatch.\n",
    "  tf_train_dataset = tf.placeholder(tf.float32,\n",
    "                                    shape=(batch_size, image_size * image_size))\n",
    "  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "  tf_valid_dataset = tf.constant(valid_dataset)\n",
    "  tf_test_dataset = tf.constant(test_dataset)\n",
    "  \n",
    "  # Variables.\n",
    "  weights_1 = tf.Variable(\n",
    "    tf.truncated_normal([image_size * image_size, hidden_nodes]))\n",
    "  biases_1 = tf.Variable(tf.zeros([hidden_nodes]))\n",
    "  weights_2 = tf.Variable(\n",
    "    tf.truncated_normal([hidden_nodes, num_labels]))\n",
    "  biases_2 = tf.Variable(tf.zeros([num_labels]))\n",
    "  \n",
    "  # Training computation.\n",
    "  def forward_prop(input):\n",
    "    h1 = tf.nn.relu(tf.matmul(input, weights_1) + biases_1)\n",
    "    return tf.matmul(h1, weights_2) + biases_2\n",
    "  \n",
    "  logits = forward_prop(tf_train_dataset)\n",
    "  loss = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "\n",
    "  # Add the regularization term to the loss.\n",
    "  loss += beta * (tf.nn.l2_loss(weights_1) + tf.nn.l2_loss(weights_2))\n",
    "  \n",
    "  # Optimizer.\n",
    "  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n",
    "  \n",
    "  # Predictions for the training, validation, and test data.\n",
    "  train_prediction = tf.nn.softmax(logits)\n",
    "  valid_prediction = tf.nn.softmax(forward_prop(tf_valid_dataset))\n",
    "  test_prediction = tf.nn.softmax(forward_prop(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 1939.758911\n",
      "Minibatch accuracy: 10.9%\n",
      "Validation accuracy: 28.2%\n",
      "Minibatch loss at step 500: 126.945297\n",
      "Minibatch accuracy: 82.8%\n",
      "Validation accuracy: 82.9%\n",
      "Minibatch loss at step 1000: 10.868656\n",
      "Minibatch accuracy: 88.3%\n",
      "Validation accuracy: 85.1%\n",
      "Minibatch loss at step 1500: 1.389078\n",
      "Minibatch accuracy: 89.8%\n",
      "Validation accuracy: 85.4%\n",
      "Minibatch loss at step 2000: 0.681626\n",
      "Minibatch accuracy: 88.3%\n",
      "Validation accuracy: 85.6%\n",
      "Minibatch loss at step 2500: 0.648225\n",
      "Minibatch accuracy: 85.2%\n",
      "Validation accuracy: 85.6%\n",
      "Minibatch loss at step 3000: 0.788015\n",
      "Minibatch accuracy: 78.9%\n",
      "Validation accuracy: 85.4%\n",
      "Test accuracy: 90.8%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 3001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print(\"Initialized\")\n",
    "  for step in range(num_steps):\n",
    "    # Pick an offset within the training data, which has been randomized.\n",
    "    # Note: we could use better randomization across epochs.\n",
    "    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "    # Generate a minibatch.\n",
    "    batch_data = train_dataset[offset:(offset + batch_size), :]\n",
    "    batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "    # Prepare a dictionary telling the session where to feed the minibatch.\n",
    "    # The key of the dictionary is the placeholder node of the graph to be fed,\n",
    "    # and the value is the numpy array to feed to it.\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "    if (step % 500 == 0):\n",
    "      print(\"Minibatch loss at step %d: %f\" % (step, l))\n",
    "      print(\"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels))\n",
    "      print(\"Validation accuracy: %.1f%%\" % accuracy(\n",
    "        valid_prediction.eval(), valid_labels))\n",
    "  print(\"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "na8xX2yHZzNF"
   },
   "source": [
    "---\n",
    "Problem 2\n",
    "---------\n",
    "Let's demonstrate an extreme case of overfitting. Restrict your training data to just a few batches. What happens?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 1843.877930\n",
      "Minibatch accuracy: 9.4%\n",
      "Validation accuracy: 22.7%\n",
      "Minibatch loss at step 500: 128.225174\n",
      "Minibatch accuracy: 99.2%\n",
      "Validation accuracy: 79.3%\n",
      "Minibatch loss at step 1000: 10.765879\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 82.5%\n",
      "Minibatch loss at step 1500: 1.253613\n",
      "Minibatch accuracy: 99.2%\n",
      "Validation accuracy: 82.2%\n",
      "Minibatch loss at step 2000: 0.430536\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 82.8%\n",
      "Minibatch loss at step 2500: 0.433309\n",
      "Minibatch accuracy: 97.7%\n",
      "Validation accuracy: 83.0%\n",
      "Minibatch loss at step 3000: 0.365732\n",
      "Minibatch accuracy: 99.2%\n",
      "Validation accuracy: 82.7%\n",
      "Test accuracy: 88.6%\n"
     ]
    }
   ],
   "source": [
    "train_dataset_restricted = train_dataset[:3000, :]\n",
    "train_labels_restricted = train_labels[:3000, :]\n",
    "\n",
    "num_steps = 3001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print(\"Initialized\")\n",
    "  for step in range(num_steps):\n",
    "    # Pick an offset within the training data, which has been randomized.\n",
    "    # Note: we could use better randomization across epochs.\n",
    "    offset = (step * batch_size) % (train_labels_restricted.shape[0] - batch_size)\n",
    "    # Generate a minibatch.\n",
    "    batch_data = train_dataset_restricted[offset:(offset + batch_size), :]\n",
    "    batch_labels = train_labels_restricted[offset:(offset + batch_size), :]\n",
    "    # Prepare a dictionary telling the session where to feed the minibatch.\n",
    "    # The key of the dictionary is the placeholder node of the graph to be fed,\n",
    "    # and the value is the numpy array to feed to it.\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "    if (step % 500 == 0):\n",
    "      print(\"Minibatch loss at step %d: %f\" % (step, l))\n",
    "      print(\"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels))\n",
    "      print(\"Validation accuracy: %.1f%%\" % accuracy(\n",
    "        valid_prediction.eval(), valid_labels))\n",
    "  print(\"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ww3SCBUdlkRc"
   },
   "source": [
    "---\n",
    "Problem 3\n",
    "---------\n",
    "Introduce Dropout on the hidden layer of the neural network. Remember: Dropout should only be introduced during training, not evaluation, otherwise your evaluation results would be stochastic as well. TensorFlow provides `nn.dropout()` for that, but you have to make sure it's only inserted during training.\n",
    "\n",
    "What happens to our extreme overfitting case?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "hidden_nodes = 1024\n",
    "learning_rate = 0.5\n",
    "beta = 0.005\n",
    "\n",
    "graph = tf.Graph()\n",
    "with graph.as_default():\n",
    "\n",
    "  # Input data. For the training data, we use a placeholder that will be fed\n",
    "  # at run time with a training minibatch.\n",
    "  tf_train_dataset = tf.placeholder(tf.float32,\n",
    "                                    shape=(batch_size, image_size * image_size))\n",
    "  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "  tf_valid_dataset = tf.constant(valid_dataset)\n",
    "  tf_test_dataset = tf.constant(test_dataset)\n",
    "\n",
    "  # Placeholder to control dropout probability.\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  \n",
    "  # Variables.\n",
    "  weights_1 = tf.Variable(\n",
    "    tf.truncated_normal([image_size * image_size, hidden_nodes]))\n",
    "  biases_1 = tf.Variable(tf.zeros([hidden_nodes]))\n",
    "  weights_2 = tf.Variable(\n",
    "    tf.truncated_normal([hidden_nodes, num_labels]))\n",
    "  biases_2 = tf.Variable(tf.zeros([num_labels]))\n",
    "  \n",
    "  # Training computation.\n",
    "  def forward_prop(input):\n",
    "    h1 = tf.nn.relu(tf.matmul(input, weights_1) + biases_1)\n",
    "    \n",
    "    # Add dropout to the hidden layer.\n",
    "    drop = tf.nn.dropout(h1, keep_prob)\n",
    "    \n",
    "    return tf.matmul(drop, weights_2) + biases_2\n",
    "  \n",
    "  logits = forward_prop(tf_train_dataset)\n",
    "  loss = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "\n",
    "  # Add the regularization term to the loss.\n",
    "  loss += beta * (tf.nn.l2_loss(weights_1) + tf.nn.l2_loss(weights_2))\n",
    "  \n",
    "  # Optimizer.\n",
    "  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n",
    "  \n",
    "  # Predictions for the training, validation, and test data.\n",
    "  train_prediction = tf.nn.softmax(logits)\n",
    "  valid_prediction = tf.nn.softmax(forward_prop(tf_valid_dataset))\n",
    "  test_prediction = tf.nn.softmax(forward_prop(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 2118.435547\n",
      "Minibatch accuracy: 14.1%\n",
      "Validation accuracy: 36.0%\n",
      "Minibatch loss at step 500: 128.232056\n",
      "Minibatch accuracy: 78.1%\n",
      "Validation accuracy: 82.4%\n",
      "Minibatch loss at step 1000: 10.991631\n",
      "Minibatch accuracy: 86.7%\n",
      "Validation accuracy: 85.0%\n",
      "Minibatch loss at step 1500: 1.463545\n",
      "Minibatch accuracy: 86.7%\n",
      "Validation accuracy: 85.1%\n",
      "Minibatch loss at step 2000: 0.784623\n",
      "Minibatch accuracy: 86.7%\n",
      "Validation accuracy: 85.2%\n",
      "Minibatch loss at step 2500: 0.701598\n",
      "Minibatch accuracy: 82.8%\n",
      "Validation accuracy: 85.1%\n",
      "Minibatch loss at step 3000: 0.880962\n",
      "Minibatch accuracy: 78.9%\n",
      "Validation accuracy: 84.8%\n",
      "Test accuracy: 90.5%\n"
     ]
    }
   ],
   "source": [
    "train_dataset_restricted = train_dataset[:3000, :]\n",
    "train_labels_restricted = train_labels[:3000, :]\n",
    "\n",
    "num_steps = 3001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print(\"Initialized\")\n",
    "  for step in range(num_steps):\n",
    "    # Pick an offset within the training data, which has been randomized.\n",
    "    # Note: we could use better randomization across epochs.\n",
    "    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "    # Generate a minibatch.\n",
    "    batch_data = train_dataset[offset:(offset + batch_size), :]\n",
    "    batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "    # Prepare a dictionary telling the session where to feed the minibatch.\n",
    "    # The key of the dictionary is the placeholder node of the graph to be fed,\n",
    "    # and the value is the numpy array to feed to it.\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob: 1.0}\n",
    "    feed_dict_w_drop = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob: 0.5}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict_w_drop)\n",
    "    if (step % 500 == 0):\n",
    "      print(\"Minibatch loss at step %d: %f\" % (step, l))\n",
    "      print(\"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels))\n",
    "      print(\"Validation accuracy: %.1f%%\" % accuracy(\n",
    "        valid_prediction.eval(feed_dict=feed_dict), valid_labels))\n",
    "  print(\"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(feed_dict=feed_dict), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "-b1hTz3VWZjw"
   },
   "source": [
    "---\n",
    "Problem 4\n",
    "---------\n",
    "\n",
    "Try to get the best performance you can using a multi-layer model! The best reported test accuracy using a deep network is [97.1%](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html?showComment=1391023266211#c8758720086795711595).\n",
    "\n",
    "One avenue you can explore is to add multiple layers.\n",
    "\n",
    "Another one is to use learning rate decay:\n",
    "\n",
    "    global_step = tf.Variable(0)  # count the number of steps taken.\n",
    "    learning_rate = tf.train.exponential_decay(0.5, global_step, ...)\n",
    "    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that I added a 2nd hidden layer in the code but then commented it out because it made the performance worse, and my VM is too slow to spend time tuning hyperparameters. You get the idea!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "hidden_nodes = 1024\n",
    "hidden_nodes_2 = 500\n",
    "beta = 0.005\n",
    "\n",
    "graph = tf.Graph()\n",
    "with graph.as_default():\n",
    "\n",
    "  # Input data. For the training data, we use a placeholder that will be fed\n",
    "  # at run time with a training minibatch.\n",
    "  tf_train_dataset = tf.placeholder(tf.float32,\n",
    "                                    shape=(batch_size, image_size * image_size))\n",
    "  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "  tf_valid_dataset = tf.constant(valid_dataset)\n",
    "  tf_test_dataset = tf.constant(test_dataset)\n",
    "\n",
    "  # Placeholder to control dropout probability.\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  \n",
    "  # Variables.\n",
    "  weights_1 = tf.Variable(tf.truncated_normal([image_size * image_size, hidden_nodes]))\n",
    "  biases_1 = tf.Variable(tf.zeros([hidden_nodes]))\n",
    "  weights_2 = tf.Variable(tf.truncated_normal([hidden_nodes, num_labels]))\n",
    "  biases_2 = tf.Variable(tf.zeros([num_labels]))\n",
    "    \n",
    "  # This is what the weights look like with an additional hidden layer.\n",
    "  # weights_2 = tf.Variable(tf.truncated_normal([hidden_nodes, hidden_nodes_2]))\n",
    "  # biases_2 = tf.Variable(tf.zeros([hidden_nodes_2]))\n",
    "  # weights_3 = tf.Variable(tf.truncated_normal([hidden_nodes_2, num_labels]))\n",
    "  # biases_3 = tf.Variable(tf.zeros([num_labels]))\n",
    "  \n",
    "  # Training computation.\n",
    "#   def forward_prop(input):\n",
    "#     h1 = tf.nn.relu(tf.matmul(input, weights_1) + biases_1)\n",
    "#     drop = tf.nn.dropout(h1, keep_prob)\n",
    "    \n",
    "#     h2 = tf.nn.relu(tf.matmul(h1, weights_2) + biases_2)\n",
    "#     drop = tf.nn.dropout(h2, keep_prob)\n",
    "    \n",
    "#     return tf.matmul(drop, weights_3) + biases_3\n",
    "\n",
    "  def forward_prop(input):\n",
    "    h1 = tf.nn.relu(tf.matmul(input, weights_1) + biases_1)\n",
    "    drop = tf.nn.dropout(h1, keep_prob)\n",
    "    \n",
    "    return tf.matmul(drop, weights_2) + biases_2\n",
    "  \n",
    "  logits = forward_prop(tf_train_dataset)\n",
    "  loss = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "\n",
    "  # Add the regularization term to the loss.\n",
    "  # loss += beta * (tf.nn.l2_loss(weights_1) + tf.nn.l2_loss(weights_2) + tf.nn.l2_loss(weights_3))\n",
    "  loss += beta * (tf.nn.l2_loss(weights_1) + tf.nn.l2_loss(weights_2))\n",
    "  \n",
    "  # Optimizer w/ learning rate decay.\n",
    "  global_step = tf.Variable(0)\n",
    "  learning_rate = tf.train.exponential_decay(0.5, global_step, 1000, 0.9)\n",
    "  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)\n",
    "  \n",
    "  # Predictions for the training, validation, and test data.\n",
    "  train_prediction = tf.nn.softmax(logits)\n",
    "  valid_prediction = tf.nn.softmax(forward_prop(tf_valid_dataset))\n",
    "  test_prediction = tf.nn.softmax(forward_prop(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 2106.596436\n",
      "Minibatch accuracy: 6.2%\n",
      "Validation accuracy: 25.3%\n",
      "Minibatch loss at step 500: 137.231522\n",
      "Minibatch accuracy: 77.3%\n",
      "Validation accuracy: 82.6%\n",
      "Minibatch loss at step 1000: 13.910622\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 84.7%\n",
      "Minibatch loss at step 1500: 2.107945\n",
      "Minibatch accuracy: 85.2%\n",
      "Validation accuracy: 85.3%\n",
      "Minibatch loss at step 2000: 0.921251\n",
      "Minibatch accuracy: 83.6%\n",
      "Validation accuracy: 84.8%\n",
      "Minibatch loss at step 2500: 0.718915\n",
      "Minibatch accuracy: 84.4%\n",
      "Validation accuracy: 85.2%\n",
      "Minibatch loss at step 3000: 0.906768\n",
      "Minibatch accuracy: 75.8%\n",
      "Validation accuracy: 85.0%\n",
      "Test accuracy: 90.8%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 3001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print(\"Initialized\")\n",
    "  for step in range(num_steps):\n",
    "    # Pick an offset within the training data, which has been randomized.\n",
    "    # Note: we could use better randomization across epochs.\n",
    "    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "    # Generate a minibatch.\n",
    "    batch_data = train_dataset[offset:(offset + batch_size), :]\n",
    "    batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "    # Prepare a dictionary telling the session where to feed the minibatch.\n",
    "    # The key of the dictionary is the placeholder node of the graph to be fed,\n",
    "    # and the value is the numpy array to feed to it.\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob: 1.0}\n",
    "    feed_dict_w_drop = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob: 0.5}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict_w_drop)\n",
    "    if (step % 500 == 0):\n",
    "      print(\"Minibatch loss at step %d: %f\" % (step, l))\n",
    "      print(\"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels))\n",
    "      print(\"Validation accuracy: %.1f%%\" % accuracy(\n",
    "        valid_prediction.eval(feed_dict=feed_dict), valid_labels))\n",
    "  print(\"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(feed_dict=feed_dict), test_labels))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "default_view": {},
   "name": "3_regularization.ipynb",
   "provenance": [],
   "version": "0.3.2",
   "views": {}
  },
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
